#include "gtime.h"
#include <QDebug>

using namespace ns_yht;

QElapsedTimer GTime::elapsedAfterTimeRefreshed;
QDateTime GTime::currentTime = QDateTime(QDate(2020, 1, 1), QTime(0, 0, 0), Qt::LocalTime);

GTime::GTime()
{
}

void GTime::init()
{
    currentTime = QDateTime::currentDateTimeUtc();
    elapsedAfterTimeRefreshed.start();
}

void GTime::setUtcTime(qint64 utime)
{
    setUtcTime(utime, currentTime.offsetFromUtc());
}

void GTime::setUtcTime(qint64 utime, qint64 offset)
{
    currentTime.setTimeSpec(Qt::UTC);
    currentTime.setSecsSinceEpoch(utime + offset);
    currentTime.setOffsetFromUtc(offset);
    elapsedAfterTimeRefreshed.start();
}

qint64 GTime::getUtcTime_s()
{
    return currentTime.toUTC().addMSecs(elapsedAfterTimeRefreshed.elapsed()).toSecsSinceEpoch();
}

// toLocalTime()这个本地时间是测试地当地时间，应该和操作系统设置的时区有关；
// 直接获取的时间是设置了时区后的时间
QDateTime GTime::getLocalTime()
{
    return currentTime.addMSecs(elapsedAfterTimeRefreshed.elapsed());
}

QDateTime GTime::getLocalTimeFromUtc(qint64 time)
{
    return QDateTime::fromSecsSinceEpoch(time + currentTime.offsetFromUtc(), currentTime.timeSpec());
}

QDateTime GTime::getUtcTime()
{
    return currentTime.toUTC().addMSecs(elapsedAfterTimeRefreshed.elapsed());
}

qint64 GTime::getMsgTime(int sec)
{
    QDateTime ct = getUtcTime();

    int ctsec = ct.time().second();
    if (ctsec == sec)
        return ct.toSecsSinceEpoch();
    if (ctsec > sec)
        ct = ct.addSecs(-(ctsec - sec));
    else
        ct = ct.addSecs(-(ctsec + 60 - sec));
    return ct.toSecsSinceEpoch();
}
